<template>
  <div class="work-container">
    <div class="header">
      <h1 class="title">学生作品</h1>
      <div class="action-buttons">
        <!-- 上传按钮已移动到选项卡内 -->
      </div>
    </div>

    <!-- 添加tab栏 -->
    <div class="tabs-container">
      <a-tabs v-model:activeKey="activeTab" type="card">
        <a-tab-pane key="theater" tab="小剧场">
          <!-- 小剧场内容 - 当前页面的内容将显示在这里 -->
          <div class="theater-content">
            <!-- 小剧场上方添加操作按钮 -->
            <div class="tab-header">
              <div>
                <!-- 将输入框移到这里 -->
                <a-input
                  v-model:value="searchParams.keyword"
                  placeholder="输入学生姓名或作品名称"
                  style="width: 220px"
                  allowClear
                  @input="handleKeywordChange"
                  @pressEnter="handleSearch"
                >
                  <template #suffix>
                    <a-button type="link" size="small" @click="handleSearch">
                      <SearchOutlined />
                    </a-button>
                  </template>
                </a-input>
              </div>
              <div class="tab-actions">
                <a-button 
                  :type="searchParams.isAward ? 'primary' : 'default'" 
                  @click="toggleAwardFilter('theater')"
                  :style="{ backgroundColor: searchParams.isAward ? '#faad14' : '', borderColor: searchParams.isAward ? '#faad14' : '' }"
                >
                  <TrophyOutlined :style="{ color: searchParams.isAward ? 'white' : '#faad14' }" />
                  作品墙
                </a-button>
                <a-button type="primary" @click="showBatchAwardModal('theater')">
                  <CrownOutlined /> 上墙展示
                </a-button>
                <a-button type="primary" @click="showUploadModal('theater')">
                  <UploadOutlined /> 上传小剧场作品
                </a-button>
              </div>
            </div>
            
            <!-- 筛选栏 -->
            <div class="filter-bar">
                <!-- 已移除筛选输入框 -->
    </div>

    <div class="works-grid">
              <div class="work-card" v-for="work in worksList" :key="work.id">
        <div class="work-preview">
                  <img v-if="work.workType === 1" :src="work.thumbnailUrl || work.fileUrl" alt="作品封面" />
                  <div v-else-if="work.workType === 2" class="video-preview">
                    <PlayCircleOutlined />
                    <img :src="work.thumbnailUrl || work.fileUrl" alt="视频封面" />
        </div>
                  <div v-else-if="work.workType === 3" class="audio-preview">
                    <SoundOutlined />
                    <img :src="work.thumbnailUrl || work.fileUrl" alt="音频封面" />
                  </div>
        </div>
                
        <div class="work-info">
          <div class="work-title">
                    {{ work.workTitle }}
                    <div class="tag-container">
                      <a-tag v-for="tag in work.tags" :key="tag.id" color="gold">
                        {{ tag.tagName }}
                      </a-tag>
          </div>
          </div>
                  
          <div class="student-info">
                    <div>{{ work.student?.userName || '未知学生' }}</div>
                    <div>{{ work.student?.className || '未分班' }}</div>
          </div>
                  
          <div class="work-meta">
                    <div class="upload-time">{{ formatDate(work.createdAt) }}</div>
                    <div class="work-actions">
                      <a-button 
                        type="link" 
                        class="award-button" 
                        @click="toggleWorkAward(work)"
                        title="点击切换冠军状态"
                      >
                        <TrophyOutlined :style="{ color: isChampionWork(work) ? '#faad14' : '#d9d9d9' }" />
                      </a-button>
                      <a-button type="link" size="small" @click="exportWork(work)">
                        <DownloadOutlined /> 导出
                      </a-button>
                    </div>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination-container">
      <div class="page-size">
        每页显示：
                <a-select v-model:value="searchParams.pageSize" style="width: 80px" @change="handlePageSizeChange">
                  <a-select-option :value="10">10条</a-select-option>
                  <a-select-option :value="20">20条</a-select-option>
                  <a-select-option :value="50">50条</a-select-option>
        </a-select>
      </div>
      
      <a-pagination 
                v-model:current="searchParams.page" 
        :total="totalItems" 
                :pageSize="searchParams.pageSize"
                @change="handlePageChange"
                showSizeChanger
                showQuickJumper
                :showTotal="total => `共 ${total} 条`"
      />
    </div>
  </div>
        </a-tab-pane>
        <a-tab-pane key="reading" tab="读一读">
          <!-- 读一读内容 -->
          <div class="reading-content">
            <!-- 读一读上方添加操作按钮 -->
            <div class="tab-header">
              <div>
                <!-- 将输入框移到这里 -->
                <a-input
                  v-model:value="searchParams.keyword"
                  placeholder="输入学生姓名或作品名称"
                  style="width: 220px"
                  allowClear
                  @input="handleKeywordChange"
                  @pressEnter="handleSearch"
                >
                  <template #suffix>
                    <a-button type="link" size="small" @click="handleSearch">
                      <SearchOutlined />
                    </a-button>
                  </template>
                </a-input>
              </div>
              <div class="tab-actions">
                <a-button 
                  :type="searchParams.isAward ? 'primary' : 'default'" 
                  @click="toggleAwardFilter('reading')"
                  :style="{ backgroundColor: searchParams.isAward ? '#faad14' : '', borderColor: searchParams.isAward ? '#faad14' : '' }"
                >
                  <TrophyOutlined :style="{ color: searchParams.isAward ? 'white' : '#faad14' }" />
                  作品墙
                </a-button>
                <a-button type="primary" @click="showBatchAwardModal('reading')">
                  <CrownOutlined /> 上墙展示
                </a-button>
                <a-button type="primary" @click="showUploadModal('reading')">
                  <UploadOutlined /> 上传阅读作品
                </a-button>
              </div>
            </div>
            
            <!-- 筛选栏 -->
            <div class="filter-bar">
                <!-- 已移除筛选输入框 -->
            </div>

            <!-- 作品网格 - 与小剧场相同的结构 -->
            <div class="works-grid" v-if="worksList.length > 0">
              <div class="work-card" v-for="work in worksList" :key="work.id">
                <div class="work-preview">
                  <img v-if="work.workType === 1" :src="work.thumbnailUrl || work.fileUrl" alt="作品封面" />
                  <div v-else-if="work.workType === 2" class="video-preview">
                    <PlayCircleOutlined />
                    <img :src="work.thumbnailUrl || work.fileUrl" alt="视频封面" />
                  </div>
                  <div v-else-if="work.workType === 3" class="audio-preview">
                    <SoundOutlined />
                    <img :src="work.thumbnailUrl || work.fileUrl" alt="音频封面" />
                  </div>
                </div>
                
                <div class="work-info">
                  <div class="work-title">
                    {{ work.workTitle }}
                    <div class="tag-container">
                      <a-tag v-for="tag in work.tags" :key="tag.id" color="gold">
                        {{ tag.tagName }}
                      </a-tag>
                    </div>
                  </div>
                  
                  <div class="student-info">
                    <div>{{ work.student?.userName || '未知学生' }}</div>
                    <div>{{ work.student?.className || '未分班' }}</div>
                  </div>
                  
                  <div class="work-meta">
                    <div class="upload-time">{{ formatDate(work.createdAt) }}</div>
                    <div class="work-actions">
                      <a-button 
                        type="link" 
                        class="award-button" 
                        @click="toggleWorkAward(work)"
                        title="点击切换冠军状态"
                      >
                        <TrophyOutlined :style="{ color: isChampionWork(work) ? '#faad14' : '#d9d9d9' }" />
                      </a-button>
                      <a-button type="link" size="small" @click="exportWork(work)">
                        <DownloadOutlined /> 导出
                      </a-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 空状态提示 - 当没有数据时显示 -->
            <div class="empty-content" v-else>
              <a-empty description="暂无音频作品" />
            </div>

            <!-- 分页器 - 与小剧场相同的结构 -->
            <div class="pagination-container" v-if="worksList.length > 0">
              <div class="page-size">
                每页显示：
                <a-select v-model:value="searchParams.pageSize" style="width: 80px" @change="handlePageSizeChange">
                  <a-select-option :value="10">10条</a-select-option>
                  <a-select-option :value="20">20条</a-select-option>
                  <a-select-option :value="50">50条</a-select-option>
                </a-select>
              </div>
              
              <a-pagination 
                v-model:current="searchParams.page" 
                :total="totalItems" 
                :pageSize="searchParams.pageSize"
                @change="handlePageChange"
                showSizeChanger
                showQuickJumper
                :showTotal="total => `共 ${total} 条`"
              />
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 上传作品模态框 -->
    <a-modal
      v-model:visible="uploadModalVisible"
      :title="uploadModalTitle"
      @ok="handleUpload"
      @cancel="cancelUpload"
      :confirmLoading="uploadLoading"
      width="600px"
    >
      <a-form
        :model="uploadForm"
        :rules="uploadRules"
        ref="uploadFormRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="作品文件" name="file" required>
          <a-upload
            v-model:file-list="fileList"
            :before-upload="beforeUpload"
            :maxCount="1"
            :accept="uploadTabType === 'theater' ? 'video/*' : 'audio/*'"
          >
            <a-button>
              <UploadOutlined /> 选择{{ uploadTabType === 'theater' ? '视频' : '音频' }}文件
            </a-button>
            <template #itemRender="{ file }">
              <div style="display: flex; align-items: center;">
                <div style="margin-right: 8px;">{{ file.name }}</div>
                <a-button type="link" danger @click="() => handleRemoveFile(file)">
                  删除
                </a-button>
              </div>
            </template>
          </a-upload>
          <div class="upload-hint">{{ uploadTabType === 'theater' ? '仅支持视频格式文件' : '仅支持音频格式文件' }}</div>
        </a-form-item>

        <a-form-item label="作品封面" name="coverFile" required>
          <a-upload
            v-model:file-list="coverFileList"
            :before-upload="beforeUploadCover"
            :maxCount="1"
            accept="image/*"
            list-type="picture-card"
          >
            <div>
              <PlusOutlined />
              <div style="margin-top: 8px">上传封面</div>
            </div>
          </a-upload>
          <div class="upload-hint">请上传作品封面图片，建议尺寸比例16:9</div>
        </a-form-item>

        <a-form-item label="作品标题" name="workTitle" required>
          <a-input 
            v-model:value="uploadForm.workTitle" 
            placeholder="请输入作品标题"
            :maxLength="500"
            show-count
          />
        </a-form-item>

        <a-form-item label="作品类型" name="workType" required>
          <a-radio-group v-model:value="uploadForm.workType" :disabled="true">
            <a-radio :value="2" v-if="uploadTabType === 'theater'">视频</a-radio>
            <a-radio :value="3" v-if="uploadTabType === 'reading'">音频</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="选择学生" name="studentId" required>
          <a-select
            v-model:value="uploadForm.studentId"
            placeholder="请选择学生"
            :options="filteredStudentOptions"
            :filter-option="filterStudentOption"
            show-search
          />
        </a-form-item>

        <a-form-item label="选择班级" name="classId" required>
          <a-select
            v-model:value="uploadForm.classId"
            placeholder="请选择班级"
            :options="studentClassList.map(c => ({ value: c.id, label: c.name }))"
            :disabled="studentClassList.length === 0"
            allowClear
          />
          <div v-if="studentClassList.length === 0 && uploadForm.studentId" class="upload-hint">
            当前学生未关联班级，请选择其他学生
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 上墙展示模态框 -->
    <a-modal
      v-model:visible="batchAwardModalVisible"
      :title="batchAwardModalTitle"
      @ok="handleBatchAward"
      @cancel="cancelBatchAward"
      :confirmLoading="batchAwardLoading"
      width="800px"
    >
      <div class="batch-award-content">
        <div class="batch-award-header">
          <div>选择要上墙展示的作品：</div>
          <div>
            <a-checkbox 
              v-model:checked="selectAll" 
              @change="handleSelectAllChange"
            >
              全选
            </a-checkbox>
          </div>
        </div>
        <a-table
          :dataSource="allWorksList"
          rowKey="id"
          :pagination="false"
          :scroll="{ y: 400 }"
          :rowSelection="{ 
            selectedRowKeys: selectedWorkIds, 
            onChange: handleSelectedWorksChange, 
            type: 'checkbox' 
          }"
        >
          <a-table-column title="作品名称" dataIndex="workTitle" />
          <a-table-column title="学生姓名" dataIndex="student" :customRender="({ record }) => record.student?.userName || '未知学生'" />
          <a-table-column title="班级" dataIndex="student" :customRender="({ record }) => record.student?.className || '未分班'" />
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { 
  LogoutOutlined, 
  DownOutlined, 
  TrophyOutlined, 
  AppstoreOutlined, 
  PlayCircleOutlined,
  SoundOutlined,
  EyeOutlined,
  LikeOutlined,
  UploadOutlined,
  DownloadOutlined,
  SearchOutlined,
  CrownOutlined,
  PlusOutlined
} from '@ant-design/icons-vue';
import { message, Upload } from 'ant-design-vue';
import dayjs from 'dayjs';
import { request } from '@/utils/request';
import { useUserStore } from '@/store/modules/user';
import type { FormInstance, UploadProps } from 'ant-design-vue';

// 接口定义
interface WorkTag {
  id: number;
  tagName: string;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
  isDelete: number;
}

interface Student {
  id: number;
  studentId: string;
  userName: string;
  school: string;
  grade: string;
  className: string;
  classId?: number; // 添加可选的classId字段
}

interface WorkItem {
  id: number;
  workId: string;
  workTitle: string;
  workDescription: string;
  workType: number; // 1-图片，2-视频，3-音频
  fileUrl: string;
  thumbnailUrl: string;
  studentId: number;
  classId: number;
  teacherId: number | null;
  viewCount: number;
  likeCount: number;
  status: number; // 0-待审核，1-已发布，2-已拒绝
  createdAt: string;
  updatedAt: string;
  isDelete: number;
  tags: WorkTag[];
  student: Student;
}

interface PaginationMeta {
  itemCount: number;
  totalItems: number;
  itemsPerPage: number;
  totalPages: number;
  currentPage: number;
}

interface ApiResponse {
  items: WorkItem[];
  meta: PaginationMeta;
}

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null;
  return (...args: any[]) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn(...args);
    }, delay) as unknown as number;
  };
};

// 当前激活的tab
const activeTab = ref('theater');
const uploadTabType = ref('theater');

// 监听标签页变化
watch(activeTab, (newTab) => {
  console.log('标签页切换:', newTab);
  // 重置分页
  searchParams.page = 1;
  // 获取新标签页对应类型的作品
  fetchWorksList();
});

// 搜索参数
const searchParams = reactive({
  page: 1,
  pageSize: 10,
  workTitle: '',
  workType: undefined as number | undefined,
  studentId: undefined as number | undefined,
  classId: undefined as number | undefined,
  status: undefined as number | undefined,
  tagId: undefined as number | undefined,
  uploadDate: undefined as string | undefined,
  keyword: '',
  isAward: false // 是否筛选冠军作品
});

// 分页数据
const totalItems = ref(0);

// 作品列表数据
const worksList = ref<WorkItem[]>([]);

// 班级列表
const classList = ref<{ id: number, name: string }[]>([]);

// 标签列表
const tagList = ref<WorkTag[]>([
  { id: 1, tagName: '优秀作品', sortOrder: 0, createdAt: '', updatedAt: '', isDelete: 0 },
  { id: 2, tagName: '推荐作品', sortOrder: 1, createdAt: '', updatedAt: '', isDelete: 0 }
]);

// 学生列表
const studentList = ref<Student[]>([]);

// 获取学生列表
const fetchStudentList = async () => {
  try {
    const response = await request('/api/manage/admin/manage/student', {
      method: 'GET',
      params: {
        page: 1,
        pageSize: 100 // 修改为API允许的最大值
      }
    });
    
    console.log('获取到的学生列表:', response);
    if (response && response.items && Array.isArray(response.items)) {
      studentList.value = response.items;
    }
  } catch (error) {
    console.error('获取学生列表失败:', error);
    message.error('获取学生列表失败，请重试');
  }
};

// 获取班级列表
const fetchClassList = async () => {
  try {
    const response = await request('/api/manage/admin/manage/class', {
      method: 'GET',
      params: {
        page: 1,
        pageSize: 100
      }
    });
    
    console.log('获取到的班级列表:', response);
    if (response && response.items && Array.isArray(response.items)) {
      classList.value = response.items.map(cls => ({
        id: cls.id,
        name: cls.className
      }));
    }
  } catch (error) {
    console.error('获取班级列表失败:', error);
    message.error('获取班级列表失败，请重试');
  }
};

// 学生选项（只包含有班级的学生）
const filteredStudentOptions = computed(() => {
  return studentList.value
    .filter(student => student.classId || (student.classes && student.classes.length > 0))
    .map(student => ({
      value: student.id,
      label: `${student.userName} (${student.studentId})`
    }));
});

// 学生搜索过滤
const filterStudentOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 上传相关
const uploadModalVisible = ref(false);
const uploadLoading = ref(false);
const uploadFormRef = ref<FormInstance>();
const fileList = ref<any[]>([]);
const coverFileList = ref<any[]>([]);

const uploadForm = reactive({
  file: undefined as File | undefined,
  coverFile: undefined as File | undefined,
  workTitle: '',
  workType: 1,
  studentId: undefined as number | undefined,
  classId: undefined as number | undefined,
  tagIds: [] as number[]
});

const uploadRules = {
  workTitle: [{ required: true, message: '请输入作品标题', trigger: 'blur' }],
  workType: [{ required: true, message: '请选择作品类型', trigger: 'change' }],
  studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  coverFile: [{ required: true, message: '请上传作品封面', trigger: 'change' }]
};

// 当前选中学生的班级列表
const studentClassList = ref<{ id: number, name: string }[]>([]);

// 监听学生选择变化
watch(() => uploadForm.studentId, async (newStudentId) => {
  if (!newStudentId) {
    studentClassList.value = [];
    uploadForm.classId = undefined;
    return;
  }
  
  // 先清空班级列表和选择
  studentClassList.value = [];
  uploadForm.classId = undefined;
  
  try {
    // 发起请求获取学生所有班级
    const response = await request(`/api/manage/admin/manage/student/${newStudentId}/classes`, {
      method: 'GET'
    });
    
    console.log('获取到的学生班级信息:', response);
    
    if (response && response.items && Array.isArray(response.items) && response.items.length > 0) {
      // 使用API返回的班级列表
      studentClassList.value = response.items.map(cls => ({
        id: cls.id,
        name: cls.className || cls.name
      }));
      console.log('学生关联的班级列表:', studentClassList.value);
    } else {
      // 后备方案：从学生对象本身获取班级信息
      const selectedStudent = studentList.value.find(student => student.id === newStudentId);
      if (selectedStudent) {
        console.log('选中的学生信息:', selectedStudent);
        
        // 检查学生是否有classes数组
        if (selectedStudent.classes && Array.isArray(selectedStudent.classes) && selectedStudent.classes.length > 0) {
          console.log('学生的classes属性:', selectedStudent.classes);
          
          const studentClasses = selectedStudent.classes.map(cls => ({
            id: cls.classId || cls.id,
            name: cls.className || cls.name
          }));
          
          if (studentClasses.length > 0) {
            studentClassList.value = studentClasses;
            console.log('从学生对象获取的班级列表:', studentClassList.value);
          }
        } 
        // 检查是否有单个班级关联
        else if (selectedStudent.classId && selectedStudent.className) {
          studentClassList.value = [{ 
            id: selectedStudent.classId, 
            name: selectedStudent.className 
          }];
          console.log('从学生对象获取的单个班级:', studentClassList.value);
        }
      }
    }
    
    // 如果没有找到任何班级，给出提示
    if (studentClassList.value.length === 0) {
      message.warning('该学生没有关联任何班级，请选择其他学生');
    } 
    // 如果只有一个班级，自动选择
    else if (studentClassList.value.length === 1) {
      uploadForm.classId = studentClassList.value[0].id;
    }
    // 有多个班级，需要用户选择
  } catch (error) {
    console.error('获取学生班级信息失败:', error);
    message.error('获取学生班级信息失败，请重试');
  }
});

// 上传模态框标题
const uploadModalTitle = computed(() => {
  return uploadTabType.value === 'theater' ? '上传小剧场作品' : '上传阅读作品';
});

// 上传前的文件处理
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  // 验证文件类型
  const isVideo = uploadTabType.value === 'theater' && file.type.startsWith('video/');
  const isAudio = uploadTabType.value === 'reading' && file.type.startsWith('audio/');
  
  if (uploadTabType.value === 'theater' && !isVideo) {
    message.error('小剧场只能上传视频文件！');
    return Upload.LIST_IGNORE;
  }
  
  if (uploadTabType.value === 'reading' && !isAudio) {
    message.error('读一读只能上传音频文件！');
    return Upload.LIST_IGNORE;
  }
  
  uploadForm.file = file;
  // 根据当前tab类型自动设置文件类型
  uploadForm.workType = uploadTabType.value === 'theater' ? 2 : 3;
  return false;
};

// 上传前的封面处理
const beforeUploadCover = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('封面只能上传图片文件!');
    return Upload.LIST_IGNORE;
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('封面图片必须小于2MB!');
    return Upload.LIST_IGNORE;
  }
  
  uploadForm.coverFile = file;
  return false;
};

// 移除文件
const handleRemoveFile = () => {
  fileList.value = [];
  uploadForm.file = undefined;
};

// 移除封面
const handleRemoveCover = () => {
  coverFileList.value = [];
  uploadForm.coverFile = undefined;
};

// 取消上传
const cancelUpload = () => {
  uploadModalVisible.value = false;
  uploadFormRef.value?.resetFields();
  fileList.value = [];
  uploadForm.file = undefined;
  coverFileList.value = [];
  uploadForm.coverFile = undefined;
  // 重置学生相关数据
  studentClassList.value = [];
};

// 显示上传模态框
const showUploadModal = (tab: string) => {
  // 打开模态框前获取最新的学生列表
  fetchStudentList();
  uploadModalVisible.value = true;
  uploadTabType.value = tab; // 记录当前上传的类型
  // 根据tab类型设置默认工作类型
  uploadForm.workType = tab === 'theater' ? 2 : 3;
};

// 处理上传
const handleUpload = () => {
  uploadFormRef.value?.validate().then(async () => {
    if (!uploadForm.file) {
      message.error('请选择要上传的文件');
      return;
    }
    
    if (!uploadForm.coverFile) {
      message.error('请上传作品封面图片');
      return;
    }
    
    if (!uploadForm.classId) {
      message.error('请选择学生所在班级');
      return;
    }
    
    uploadLoading.value = true;
    
    try {
      // 获取token用于认证
      const userStore = useUserStore();
      const token = userStore.token;
      const baseUrl = import.meta.env.VITE_BASE_API_URL || '';
      const url = `${baseUrl}/api/manage/wall/upload`;
      
      // 确保FormData正确初始化
      const formData = new FormData();
      
      // 添加文件，明确指定文件名
      formData.append('file', uploadForm.file, uploadForm.file.name);
      formData.append('cover', uploadForm.coverFile, uploadForm.coverFile.name);
      
      // 添加字段（确保字段名与后端匹配，并转换为字符串）
      formData.append('workTitle', String(uploadForm.workTitle.trim()));
      formData.append('workType', String(uploadForm.workType));
      formData.append('studentId', String(uploadForm.studentId));
      
      // 添加班级ID
      if (uploadForm.classId) {
        formData.append('classId', String(uploadForm.classId));
      }
      
      // 打印FormData内容
      console.log('===== FormData内容 =====');
      for (const [key, value] of formData.entries()) {
        if (value instanceof File) {
          console.log(`${key}: [文件] 名称=${value.name}, 类型=${value.type}, 大小=${value.size}字节`);
        } else {
          console.log(`${key}: ${value}`);
        }
      }
      
      // 使用XMLHttpRequest发送请求，这样可以监控请求头和请求体
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        
        // 打开一个连接
        xhr.open('POST', url, true);
        
        // 设置请求头
        if (token) {
          xhr.setRequestHeader('Authorization', `Bearer ${token}`);
        }
        
        // 监听上传进度
        xhr.upload.onprogress = (event) => {
          if (event.lengthComputable) {
            const percentComplete = (event.loaded / event.total) * 100;
            console.log(`上传进度: ${percentComplete.toFixed(2)}%`);
          }
        };
        
        // 监听请求完成
        xhr.onload = function() {
          if (xhr.status >= 200 && xhr.status < 300) {
            // 打印响应头
            console.log('===== 响应头信息 =====');
            const headers = xhr.getAllResponseHeaders();
            const headerArr = headers.trim().split(/[\r\n]+/);
            const headerMap = {};
            headerArr.forEach((line) => {
              const parts = line.split(': ');
              const header = parts.shift();
              const value = parts.join(': ');
              headerMap[header] = value;
            });
            console.log(headerMap);
            
            // 打印响应体
            console.log('===== 响应体信息 =====');
            let responseData;
            try {
              responseData = JSON.parse(xhr.responseText);
            } catch (e) {
              responseData = xhr.responseText;
            }
            console.log(responseData);
            
            // 成功处理
            message.success('作品上传成功');
            
            // 关闭模态框并刷新列表
            uploadModalVisible.value = false;
            uploadFormRef.value?.resetFields();
            fileList.value = [];
            uploadForm.file = undefined;
            coverFileList.value = [];
            uploadForm.coverFile = undefined;
            // 重置学生相关数据
            studentClassList.value = [];
            fetchWorksList();
            
            resolve(responseData);
          } else {
            const error = new Error(`上传失败，状态码: ${xhr.status}`);
            console.error('上传失败:', error);
            message.error('作品上传失败，请重试');
            reject(error);
          }
        };
        
        // 错误处理
        xhr.onerror = function() {
          const error = new Error('网络请求失败');
          console.error('上传失败:', error);
          message.error('网络请求失败，请检查网络连接');
          reject(error);
        };
        
        // 请求发送前打印请求头信息
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 1) { // OPENED
            console.log('===== 准备发送请求 =====');
            console.log('请求URL:', url);
            console.log('请求方法:', 'POST');
            console.log('Authorization:', token ? `Bearer ${token}` : '未设置');
            
            // 注意：浏览器限制，无法获取自动生成的Content-Type
            console.log('Content-Type:', 'multipart/form-data (将由浏览器自动设置boundary)');
          }
        };
        
        // 发送请求
        xhr.send(formData);
        
        // 打印到浏览器控制台
        console.log('===== 请求已发送 =====');
        console.log('使用 Network 面板查看完整请求详情，包括自动设置的Content-Type和boundary参数');
      });
      
    } catch (error) {
      console.error('上传失败:', error);
      message.error('作品上传失败，请重试');
    } finally {
      uploadLoading.value = false;
    }
  }).catch(error => {
    console.log('表单验证失败:', error);
  });
};

// 格式化日期
const formatDate = (dateStr: string) => {
  return dayjs(dateStr).format('YYYY.MM.DD');
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待审核',
    1: '已发布',
    2: '已拒绝'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态类名
const getStatusClass = (status: number) => {
  const statusClassMap: Record<number, string> = {
    0: 'status-pending',
    1: 'status-published',
    2: 'status-rejected'
  };
  return statusClassMap[status] || '';
};

// 搜索处理
const handleSearch = () => {
  console.log('执行搜索，关键词:', searchParams.keyword);
  searchParams.page = 1; // 重置到第一页
  fetchWorksList(); // 立即执行搜索，不使用防抖
};

// 日期变更
const onDateChange = (date: any) => {
  searchParams.uploadDate = date ? dayjs(date).format('YYYY-MM-DD') : undefined;
  handleSearch();
};

// 状态筛选
const onStatusChange = (e: any) => {
  searchParams.status = e.key ? parseInt(e.key) : undefined;
  handleSearch();
};

// 班级筛选
const onClassChange = (e: any) => {
  searchParams.classId = e.key ? parseInt(e.key) : undefined;
  handleSearch();
};

// 作品类型筛选
const onTypeChange = (e: any) => {
  searchParams.workType = e.key ? parseInt(e.key) : undefined;
  handleSearch();
};

// 标签筛选
const onTagChange = (e: any) => {
  searchParams.tagId = e.key ? parseInt(e.key) : undefined;
  handleSearch();
};

// 页码变更
const handlePageChange = (page: number) => {
  searchParams.page = page;
  fetchWorksList();
};

// 每页条数变更
const handlePageSizeChange = (pageSize: number) => {
  searchParams.pageSize = pageSize;
  searchParams.page = 1; // 重置到第一页
  fetchWorksList();
};

// 查看作品详情
const viewWorkDetail = (work: WorkItem) => {
  message.info(`查看作品详情：${work.workTitle}`);
  // 实际项目中可以跳转到详情页或打开详情模态框
};

// 获取作品列表
const fetchWorksList = async () => {
  try {
    // 根据当前活动标签设置正确的workType
    let tabWorkType: number | undefined;
    if (activeTab.value === 'theater') {
      tabWorkType = 2; // 小剧场标签只获取视频(workType=2)
    } else if (activeTab.value === 'reading') {
      tabWorkType = 3; // 读一读标签只获取音频(workType=3)
    }
    
    // 用户手动设置的workType优先级高于自动设置的
    const finalWorkType = searchParams.workType || tabWorkType;
    
    // 打印请求参数日志，便于调试
    console.log('=== 发送API请求前参数日志 ===');
    console.log('当前激活的标签页:', activeTab.value);
    console.log('标签页对应的作品类型:', tabWorkType);
    console.log('用户手动选择的作品类型:', searchParams.workType);
    console.log('最终使用的作品类型:', finalWorkType);
    console.log('搜索关键词:', searchParams.keyword);
    
    const params = {
      page: searchParams.page,
      pageSize: searchParams.pageSize,
      workTitle: searchParams.workTitle || searchParams.keyword || undefined,
      studentName: searchParams.keyword || undefined,
      workType: finalWorkType,
      studentId: searchParams.studentId,
      classId: searchParams.classId,
      status: searchParams.isAward ? 1 : searchParams.status, // 当isAward为true时，设置status=1筛选冠军作品
      tagId: searchParams.tagId, // 不再使用tagId来标识冠军作品
      tabType: activeTab.value // 传递当前激活的tab
    };
    
    console.log('完整请求参数:', params);
    
    const response = await request<ApiResponse>('/api/manage/wall', {
      method: 'GET',
      params
    });
    
    // 打印后端响应数据，帮助调试
    console.log('=== API响应数据日志 ===');
    console.log('响应状态:', '成功');
    console.log('响应数据类型:', typeof response);
    console.log('返回项目数量:', response.items?.length || 0);
    console.log('返回总数量:', response.meta?.totalItems || 0);
    
    // 打印完整的原始响应数据（如果有数据的话）
    if (response.items && response.items.length > 0) {
      console.log('=== 原始响应数据示例（第一条作品完整数据）===');
      console.log(JSON.stringify(response.items[0], null, 2));
    }
    
    // 第一个作品示例信息（简化版）
    if (response.items && response.items.length > 0) {
      console.log('第一个作品示例:', {
        id: response.items[0].id,
        workTitle: response.items[0].workTitle,
        workType: response.items[0].workType,
        studentName: response.items[0].student?.userName
      });
    } else {
      console.log('未返回任何作品数据');
    }
    
    // 如果返回了数据，但用户提供了搜索关键词，再次在前端过滤结果
    let filteredItems = response.items;
    if (searchParams.keyword && filteredItems && filteredItems.length > 0) {
      const keyword = searchParams.keyword.toLowerCase();
      console.log('正在前端过滤关键词:', keyword);
      
      filteredItems = filteredItems.filter(item => {
        // 匹配作品标题
        const titleMatch = item.workTitle && item.workTitle.toLowerCase().includes(keyword);
        // 匹配学生姓名
        const studentMatch = item.student && item.student.userName && 
                             item.student.userName.toLowerCase().includes(keyword);
        // 匹配学生ID
        const studentIdMatch = item.student && item.student.studentId && 
                               item.student.studentId.toLowerCase().includes(keyword);
        // 返回任意一个匹配结果
        return titleMatch || studentMatch || studentIdMatch;
      });
      
      console.log('前端过滤后的结果数量:', filteredItems.length);
    }
    
    // 详细打印每个作品的类型
    if (filteredItems && filteredItems.length > 0) {
      console.log('=== 返回作品类型统计 ===');
      const workTypeStats = {
        image: 0, // 类型1：图片
        video: 0, // 类型2：视频
        audio: 0, // 类型3：音频
        other: 0  // 其他类型
      };
      
      filteredItems.forEach(item => {
        if (item.workType === 1) workTypeStats.image++;
        else if (item.workType === 2) workTypeStats.video++;
        else if (item.workType === 3) workTypeStats.audio++;
        else workTypeStats.other++;
      });
      
      console.log('作品类型统计:', workTypeStats);
    }
    
    // 更新数据，使用可能经过前端过滤的列表
    worksList.value = filteredItems || [];
    // 总数量可能需要调整
    totalItems.value = searchParams.keyword ? worksList.value.length : response.meta.totalItems;
  } catch (error) {
    console.error('获取作品列表失败', error);
    console.error('错误详情:', JSON.stringify(error, null, 2));
    message.error('获取作品列表失败，请重试');
    // 发生错误时清空列表
    worksList.value = [];
    totalItems.value = 0;
  }
};

// 学生筛选
const handleStudentChange = (value: number | undefined) => {
  searchParams.studentId = value;
  handleSearch();
};

// 班级筛选
const handleClassChange = (value: number | undefined) => {
  searchParams.classId = value;
  handleSearch();
};

// 导出单个作品
const exportWork = async (work: WorkItem) => {
  try {
    console.log('导出作品请求参数:', { id: work.id });
    
    message.loading('正在导出作品...');
    
    // 获取token用于认证
    const userStore = useUserStore();
    const token = userStore.token;
    
    // 直接使用原生fetch API请求文件流，绕过request函数的data.data处理逻辑
    const response = await fetch(`${import.meta.env.VITE_BASE_API_URL}/api/manage/wall/${work.id}/export`, {
      method: 'GET',
      headers: {
        'Authorization': token ? `Bearer ${token}` : ''
      }
    });
    
    // 检查响应状态码
    if (!response.ok) {
      throw new Error('导出失败，服务器返回状态码: ' + response.status);
    }
    
    // 获取响应的blob数据
    const blob = await response.blob();
    
    // 检查blob是否存在
    if (!blob) {
      throw new Error('导出失败，未收到有效的文件数据');
    }
    
    // 打印响应信息到控制台
    console.log('导出作品响应成功:', { 
      type: blob.type,
      size: blob.size 
    });
    
    // 生成文件名
    let filename = work.workTitle;
    
    // 从Content-Disposition获取文件名(如果存在)
    const contentDisposition = response.headers.get('content-disposition');
    if (contentDisposition) {
      const filenameMatch = /filename="(.+)"/.exec(contentDisposition);
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1];
      }
    } else {
      // 根据作品类型添加适当的扩展名
      if (work.workType === 1) filename += '.jpg';
      else if (work.workType === 2) filename += '.mp4';
      else if (work.workType === 3) filename += '.mp3';
      else filename += '.dat';
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    
    // 清理
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
    
    message.success(`${work.workTitle} 导出成功`);
  } catch (error) {
    console.error('导出作品失败:', error);
    message.error('导出作品失败，请重试');
  }
};

// 关键词筛选 (使用防抖优化)
const handleKeywordChange = debounce(() => {
  console.log('搜索关键词:', searchParams.keyword);
  searchParams.page = 1; // 重置到第一页
  fetchWorksList(); // 获取符合关键词的作品列表
}, 500); // 500ms防抖延迟

// 切换冠军作品筛选
const toggleAwardFilter = (tab: string) => {
  // 更新当前激活的tab
  activeTab.value = tab;
  // 切换筛选状态
  searchParams.isAward = !searchParams.isAward;
  // 重置页码
  searchParams.page = 1;
  // 获取作品列表
  fetchWorksList();
};

// 上墙展示相关
const batchAwardModalVisible = ref(false);
const batchAwardLoading = ref(false);
const currentBatchTabType = ref('theater');
const allWorksList = ref<WorkItem[]>([]);
const selectedWorkIds = ref<number[]>([]);
const selectAll = ref(false);

// 上墙展示模态框标题
const batchAwardModalTitle = computed(() => {
  return currentBatchTabType.value === 'theater' ? '小剧场作品上墙展示' : '阅读作品上墙展示';
});

// 显示上墙展示模态框
const showBatchAwardModal = async (tab: string) => {
  currentBatchTabType.value = tab;
  batchAwardModalVisible.value = true;
  selectedWorkIds.value = [];
  selectAll.value = false;
  await fetchAllWorks(tab);
};

// 取消上墙展示
const cancelBatchAward = () => {
  batchAwardModalVisible.value = false;
  allWorksList.value = [];
  selectedWorkIds.value = [];
  selectAll.value = false;
};

// 获取所有作品
const fetchAllWorks = async (tab: string) => {
  try {
    // 根据标签类型设置workType
    const tabWorkType = tab === 'theater' ? 2 : tab === 'reading' ? 3 : undefined;
    
    // 使用分页方式获取所有数据，每页最多获取100条
    let allWorks: WorkItem[] = [];
    let currentPage = 1;
    let hasMoreData = true;
    
    while (hasMoreData) {
      const response = await request<ApiResponse>('/api/manage/wall', {
        method: 'GET',
        params: {
          page: currentPage,
          pageSize: 100, // 使用最大允许值100
          tabType: tab,   // 传递当前激活的tab类型
          workType: tabWorkType, // 传递对应的作品类型
          status: 0  // 只获取普通作品(status=0)，不获取冠军作品(status=1)
        }
      });
      
      if (response.items && response.items.length > 0) {
        allWorks = [...allWorks, ...response.items];
        
        // 判断是否还有更多数据
        if (response.items.length < 100 || currentPage * 100 >= response.meta.totalItems) {
          hasMoreData = false;
        } else {
          currentPage++;
        }
      } else {
        hasMoreData = false;
      }
    }
    
    allWorksList.value = allWorks;
  } catch (error) {
    console.error('获取作品列表失败', error);
    message.error('获取作品列表失败，请重试');
  }
};

// 处理全选
const handleSelectAllChange = (e: any) => {
  if (e.target.checked) {
    selectedWorkIds.value = allWorksList.value.map(work => work.id);
  } else {
    selectedWorkIds.value = [];
  }
};

// 处理选择变化
const handleSelectedWorksChange = (selectedRowKeys: number[]) => {
  selectedWorkIds.value = selectedRowKeys;
  selectAll.value = selectedRowKeys.length === allWorksList.value.length;
};

// 处理批量上墙
const handleBatchAward = async () => {
  if (selectedWorkIds.value.length === 0) {
    message.warning('请选择要上墙展示的作品');
    return;
  }
  
  batchAwardLoading.value = true;
  
  try {
    // 使用PATCH方法请求新的批量切换状态API
    const response = await request('/api/manage/wall/batch/toggle-status', {
      method: 'PATCH',
      data: {
        ids: selectedWorkIds.value
      }
    });
    
    // 打印响应数据
    console.log('=== 批量上墙响应数据 ===');
    console.log('响应数据类型:', typeof response);
    console.log('完整原始响应数据:', JSON.stringify(response, null, 2));
    
    message.success(`已成功将${selectedWorkIds.value.length}个作品设置为冠军作品`);
    
    // 关闭模态框并刷新列表
    batchAwardModalVisible.value = false;
    fetchWorksList();
  } catch (error) {
    console.error('批量上墙失败:', error);
    console.error('错误详情:', JSON.stringify(error, null, 2));
    message.error('批量设置冠军作品失败，请重试');
  } finally {
    batchAwardLoading.value = false;
  }
};

// 判断作品是否为冠军作品
const isChampionWork = (work: WorkItem) => {
  // 直接根据作品的status字段判断，status=1表示冠军作品
  // 使用==而不是===，以处理status可能是数字1或字符串"1"的情况
  return work.status == 1;
};

// 切换作品冠军状态
const toggleWorkAward = async (work: WorkItem) => {
  try {
    console.log('切换作品冠军状态:', work.id);
    
    // 使用PATCH方法请求API，符合接口文档规范
    // 不需要传递请求体，API会自动切换状态
    const response = await request(`/api/manage/wall/${work.id}`, {
      method: 'PATCH'
    });
    
    // 打印原始响应数据
    console.log('=== 作品状态切换响应数据 ===');
    console.log('响应数据类型:', typeof response);
    console.log('完整原始响应数据:', JSON.stringify(response, null, 2));
    
    // 根据返回数据的status字段判断切换后的状态
    const newStatus = response.status;
    const wasChampion = isChampionWork(work);
    const isNowChampion = newStatus === 1;
    
    // 根据状态变化提示用户
    if (wasChampion && !isNowChampion) {
      message.success(`已取消作品"${work.workTitle}"的冠军状态`);
    } else if (!wasChampion && isNowChampion) {
      message.success(`已将作品"${work.workTitle}"设为冠军作品`);
    } else {
      message.success('作品状态已更新');
    }
    
    // 刷新作品列表
    fetchWorksList();
  } catch (error) {
    console.error('切换冠军状态失败:', error);
    console.error('错误详情:', JSON.stringify(error, null, 2));
    message.error('操作失败，请重试');
  }
};

onMounted(() => {
  fetchWorksList();
  fetchStudentList();
  fetchClassList();
});
</script>

<style scoped lang="less">
.work-container {
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .title {
    font-size: 20px;
    font-weight: bold;
  }
  
  .action-buttons {
    display: flex;
    align-items: center;
  }
}

.tabs-container {
  margin-bottom: 16px;
}

/* 添加选项卡内容头部样式 */
.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .tab-actions {
    display: flex;
    gap: 8px;
  }
}

.empty-content {
  padding: 40px 0;
  background-color: #fafafa;
  border-radius: 4px;
}

.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
  
  .work-card {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    overflow: hidden;
    
    .work-preview {
      position: relative;
      height: 160px;
      overflow: hidden;
      background-color: #f5f5f5;
      display: flex;
      justify-content: center;
      align-items: center;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .video-preview {
        position: relative;
        width: 100%;
        height: 100%;
        
        .anticon {
        position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 48px;
          color: rgba(255, 255, 255, 0.8);
          z-index: 1;
        }
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .audio-preview {
        position: relative;
        width: 100%;
        height: 100%;
        
        .anticon {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 48px;
          color: rgba(24, 144, 255, 0.9);
          z-index: 1;
        }
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          opacity: 0.85;
        }
      }
    }
    
    .work-info {
      padding: 12px;
      
      .work-title {
        font-weight: bold;
        margin-bottom: 8px;
        display: flex;
        flex-direction: column;
        
        .tag-container {
          margin-top: 4px;
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
        }
      }
      
      .student-info {
        display: flex;
        justify-content: space-between;
        font-size: 13px;
        color: #666;
        margin-bottom: 8px;
      }
      
      .work-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #999;
        margin-bottom: 8px;
        
        .upload-time {
          display: flex;
          align-items: center;
        }
        
        .work-actions {
          display: flex;
          align-items: center;
          
          .award-button {
            padding: 0 4px;
            margin-right: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .anticon {
              font-size: 16px;
            }
          }
        }
      }
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .page-size {
    display: flex;
    align-items: center;
  }
}

.upload-hint {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 筛选栏样式 */
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .filter-item {
    display: flex;
    align-items: center;
    
    .filter-label {
      margin-right: 8px;
    }
  }
}

/* 批量上墙模态框样式 */
.batch-award-content {
  .batch-award-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    font-weight: bold;
  }
}
</style>